import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_learning/memo_s3/s3_controller.dart';

class ControllerWidget extends StatefulWidget {
  const ControllerWidget({Key? key}) : super(key: key);

  @override
  State<ControllerWidget> createState() => _ControllerWidgetState();
}

class _ControllerWidgetState extends State<ControllerWidget> {
  final S3Controller _controller = S3Controller();
  bool _isConnected = false;
  Map<String, dynamic> _buttonStates = {};
  Map<String, int> _joystick = {'leftX': 128, 'leftY': 128, 'rightX': 128, 'rightY': 128};

  @override
  void initState() {
    super.initState();
    _controller.onButtonPressed = (data) {
      setState(() {
        _buttonStates = data['buttons'];
        _joystick = data['joystick'];
      });
    };
  }

  @override
  void dispose() {
    _controller.disconnect();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('S3手柄控制器')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _isConnected ? _disconnect : _connect,
              child: Text(_isConnected ? '断开连接' : '连接手柄'),
            ),
            const SizedBox(height: 20),
            if (_isConnected) ...[
              const Text('手柄状态:', style: TextStyle(fontSize: 18)),
              const SizedBox(height: 10),
              _buildButtonGrid(),
              const SizedBox(height: 20),
              _buildJoystickDisplay(),
            ],
          ],
        ),
      ),
    );
  }

  // 连接手柄
  Future<void> _connect() async {
    List<BluetoothDevice> devices = await _controller.scanDevices();

    if (devices.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('未发现S3手柄设备')));
      return;
    }

    bool connected = await _controller.connect(devices.first);

    setState(() {
      _isConnected = connected;
    });

    if (!connected) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('连接失败，请重试')));
    }
  }

  // 断开连接
  void _disconnect() {
    _controller.disconnect();
    setState(() {
      _isConnected = false;
    });
  }

  // 构建按钮状态网格
  Widget _buildButtonGrid() {
    return GridView.count(
      shrinkWrap: true,
      crossAxisCount: 4,
      padding: const EdgeInsets.all(10),
      children: [
        _buildButtonTile('A', _buttonStates['a'] ?? false),
        _buildButtonTile('B', _buttonStates['b'] ?? false),
        _buildButtonTile('X', _buttonStates['x'] ?? false),
        _buildButtonTile('Y', _buttonStates['y'] ?? false),
        _buildButtonTile('L1', _buttonStates['l1'] ?? false),
        _buildButtonTile('R1', _buttonStates['r1'] ?? false),
        _buildButtonTile('Select', _buttonStates['select'] ?? false),
        _buildButtonTile('Start', _buttonStates['start'] ?? false),
      ],
    );
  }

  // 构建单个按钮状态显示
  Widget _buildButtonTile(String label, bool pressed) {
    return Container(
      margin: const EdgeInsets.all(5),
      decoration: BoxDecoration(
        color: pressed ? Colors.green : Colors.grey,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Center(
        child: Text(label, style: const TextStyle(color: Colors.white)),
      ),
    );
  }

  // 构建摇杆显示
  Widget _buildJoystickDisplay() {
    return Column(
      children: [
        const Text('左摇杆:', style: TextStyle(fontSize: 16)),
        const SizedBox(height: 10),
        Container(
          width: 200,
          height: 200,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(100),
          ),
          child: Stack(
            children: [
              Center(
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  transform: Matrix4.translationValues(
                      (_joystick['leftX']! - 128) * 0.7, (_joystick['leftY']! - 128) * 0.7, 0),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 20),
        Text('X: ${_joystick['leftX']}, Y: ${_joystick['leftY']}'),
      ],
    );
  }
}
